<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2020-05-07
 */

namespace app\api\model\v1;

use think\Db;
use think\Cache;
use think\Config;

/**
 * 微信小程序商城购物车模型
 */
load_trait('controller/Jump');

class ShopCart extends UserBase
{
    use \traits\controller\Jump;

    private $miniproInfo = [];

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        $dataConf = tpSetting("OpenMinicode.conf_".self::$provider);
        $this->miniproInfo = json_decode($dataConf, true);
        // 购物车数据表名
        $this->shopCartDb = Db::name('shop_cart');
        // 商城订单数据模型
        $this->shopGoodsModel = model('v1.ShopGoods');
    }

    public function getCartTotalNum()
    {
        $cart_total_num = 0;
        if (!empty($this->users_id)) {
            $cart_total_num = $this->shopCartDb->where(['users_id' => $this->users_id])->sum('product_num');
        }
        return $cart_total_num;
    }

    // 购物车数据列表
    public function getCartList($levelDiscount = 100)
    {
        $result = [];
        if (!empty($this->users_id)) {
            $times = getTime();
            // 查询用户购物车商品
            $where = [
                'users_id' => $this->users_id,
            ];
            $product_ids = Db::name('shop_cart')->field('product_id, spec_value_id')->where($where)->select();
            // 检测是否存在异常商品
            $abnormalGoodsID = $this->shopGoodsModel->detectAbnormalGoods($product_ids, true);
            // 将用户购物车商品设为无异常
            $this->shopCartDb->where($where)->update(['abnormal' => 0, 'update_time' => $times]);
            // 若返回异常商品ID组则执行更新购物车商品为异常商品
            if (!empty($abnormalGoodsID)) {
                foreach ($abnormalGoodsID as $key => $value) {
                    if (!empty($value)) $this->shopCartDb->where($value)->update(['abnormal' => 1, 'update_time' => $times]);
                }
            }

            // 会员折扣
            $usersDiscount = floatval($levelDiscount) / floatval(100);

            // 获取商城配置信息
            $shopOpenSpec = intval(getUsersConfigData('shop.shop_open_spec'));

            // 计算购物车选中数商品总价、选中商品数、是否全选
            $result['cartGlobal'] = $this->getCartGoodsHandleResult($this->users_id, $shopOpenSpec, $usersDiscount);

            // 查询购物车数据
            $where = [
                'a.abnormal' => 0,
                'a.users_id' => intval($this->users_id),
                'b.arcrank'  => array('egt', 0)
            ];
            $field = 'a.*, b.aid, b.title, b.litpic, b.users_price, b.stock_count, b.attrlist_id, b.goods_spec, b.goods_unit, c.spec_price, c.spec_stock';
            if ('v1.5.1' < getVersion()) {
                $field .= ',c.seckill_price, c.seckill_stock';
            }
            if ('v1.5.7' < getVersion()) {
                $field .= ',c.discount_price, c.discount_stock';
            }
            $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
            $data = $this->shopCartDb->alias('a')
                ->field($field)
                ->join('__ARCHIVES__ b', 'a.product_id = b.aid', 'LEFT')
                ->join('__PRODUCT_SPEC_VALUE__ c', 'a.spec_value_id = c.spec_value_id and a.product_id = c.aid', 'LEFT')
                ->where($where)
                ->order('a.selected desc, a.cart_id desc')
                ->paginate($pagesize, false, ['query' => request()->param()]);
            !empty($data) && $shopCart = $data->toArray();
            // 处理购物车数据
            $result['shopCart'] = $shopCart;
            if (!empty($shopCart['data'])) {
                $result['shopCart']['data'] = $this->shopGoodsModel->getGoodsHandleResult($shopCart['data'], $usersDiscount, 'shopCart');
            }

            // 查询异常商品返回
            $where = [
                'a.abnormal' => 1,
                'a.users_id' => $this->users_id,
                'b.arcrank'  => array('egt', 0)
            ];
            $abnormalGoods = $this->shopCartDb->alias('a')
                ->field($field)
                ->join('__ARCHIVES__ b', 'a.product_id = b.aid', 'LEFT')
                ->join('__PRODUCT_SPEC_VALUE__ c', 'a.spec_value_id = c.spec_value_id and a.product_id = c.aid', 'LEFT')
                ->where($where)
                ->select();
            $result['abnormalGoods'] = [];
            // 处理购物车数据
            if (!empty($abnormalGoods)) {
                $result['abnormalGoods'] = $this->shopGoodsModel->getGoodsHandleResult($abnormalGoods, $usersDiscount, 'abnormal');
            }
        }

        return $result;
    }

    // 添加购物车商品 或 商品数量
    public function addCartGoods($post = [])
    {
        // 参数处理
        $post['product_id'] = !empty($post['product_id']) ? intval($post['product_id']) : 0;
        $post['product_num'] = !empty($post['product_num']) ? intval($post['product_num']) : 0;
        $post['spec_value_id'] = !empty($post['spec_value_id']) ? strval($post['spec_value_id']) : '';

        // 检测提交的商品是否可购买
        $this->shopGoodsModel->detectionGoods($post);

        // 查询商品是否存在
        $where = [
            'aid' => $post['product_id'],
            'status' => 1,
            'is_del' => 0,
            'arcrank' => ['>=', 0]
        ];
        $isCount = Db::name('archives')->where($where)->count();
        // 加入购物车
        if (!empty($isCount)) {
            // 查询购物车是否存在这个商品
            $where = [
                'users_id' => $this->users_id,
                'product_id' => $post['product_id'],
            ];
            // 多规格查询
            if (!empty($post['spec_value_id'])) {
                $where['spec_value_id'] = $post['spec_value_id'];
            }
            // 折扣商品查询
            if (!empty($post['discount_active_id'])) {
                $where['discount_active_id'] = $post['discount_active_id'];
            } else {
                $where['discount_active_id'] = 0;
            }
            $isCount = $this->shopCartDb->where($where)->count();
            if (!empty($isCount)) {
                // 购物车内已有相同商品，进行数量增加
                $resultID = $this->shopCartDb->where($where)->setInc('product_num', $post['product_num']);
            } else {
                // 购物车内还未有相同商品，进行添加
                $insert = [
                    'users_id' => $this->users_id,
                    'product_id' => $post['product_id'],
                    'product_num' => $post['product_num'],
                    'spec_value_id' => !empty($post['spec_value_id']) ? $post['spec_value_id'] : '',
                    'add_time' => getTime(),
                    'update_time' => getTime(),
                    'discount_active_id' => !empty($post['discount_active_id']) ? $post['discount_active_id'] : 0
                ];
                $resultID = $this->shopCartDb->insertGetId($insert);
            }
            if (!empty($resultID)) {
                $totalCart = $this->shopCartDb->where(['users_id' => $this->users_id])->sum('product_num');
                $this->success('加入成功', '', ['cart_total_num' => $totalCart]);
            } else {
                $this->error('加入失败');
            }
        } else {
            $this->error('商品已下架');
        }
    }

    // 删除购物车商品
    public function delCartGoods($param = [])
    {
        if (empty($param['checked']) && empty($param['cart_id'])) $this->error('选择要删除的商品');
        $where = [
            'cart_id' => intval($param['cart_id']),
            'users_id' => intval($this->users_id),
        ];
        if (!empty($param['checked']) && empty($param['cart_id'])) {
            $where['selected'] = 1;
            unset($where['cart_id']);
        }
        $resultID = $this->shopCartDb->where($where)->delete(true);
        if (!empty($resultID)) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    // 移除购物车商品
    public function removeCartGoods($param = [])
    {
        if (empty($param['cart_id']) || empty($param['goods_id'])) $this->error('请选择移除商品');
        $param['cart_id'] = is_array($param['cart_id']) ? $param['cart_id'] : [$param['cart_id']];
        $where = [
            'cart_id' => ['IN', $param['cart_id']],
            'users_id' => intval($this->users_id),
            'product_id' => intval($param['goods_id'])
        ];
        $update = [
            'selected' => 0,
            'update_time' => getTime()
        ];
        $resultID = $this->shopCartDb->where($where)->update($update);
        if (!empty($resultID)) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    // 删除购物车商品
    public function abnormalCartGoods($param = [])
    {
        $where = [
            'abnormal' => 1,
            'users_id' => intval($this->users_id)
        ];
        if (!empty($param['cart_id'])) $where['cart_id'] = $param['cart_id'];
        $resultID = Db::name('shop_cart')->where($where)->delete(true);
        if (!empty($resultID)) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    // 购物车商品数量更新操作
    public function updateCartGoodsNumber($param = [])
    {
        if (empty($param['cart_id']) || empty($param['product_num'])) $this->error('数据错误，请重试');
        $where = [
            'cart_id' => intval($param['cart_id']),
            'users_id' => intval($this->users_id),
        ];
        $update = [
            'product_num' => intval($param['product_num']),
            'update_time' => getTime()+10
        ];
        $resultID = $this->shopCartDb->where($where)->update($update);
        if (!empty($resultID)) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    // 购物车商品更新是否选中
    public function updateCartSelected($param = [])
    {
        // 查询需要取消选中的购物车ID
        $where = [
            'users_id' => intval($this->users_id),
        ];
        if (!empty($param['cart_ids'])) $where['cart_id'] = ['NOT IN', $param['cart_ids']];
        $cart_ids = $this->shopCartDb->where($where)->column('cart_id');
        
        // 更新选中的购物车ID
        if (!empty($param['cart_ids'])) $where['cart_id'] = ['IN', $param['cart_ids']];
        $update = [
            'selected' => 1,
            'update_time' => getTime()+10
        ];
        $resultID = $this->shopCartDb->where($where)->update($update);

        // 更新取消选中的购物车ID
        if (!empty($cart_ids)) {
            $where = [
                'cart_id' => ['IN', $cart_ids],
                'users_id' => intval($this->users_id),
            ];
            $update = [
                'selected' => 0,
                'update_time' => getTime()+10
            ];
            $resultID = $this->shopCartDb->where($where)->update($update);
        }

        if (!empty($resultID)) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    // 全选/反选
    public function updateCartAllSelected($param = [])
    {
        $where = [
            'users_id' => intval($this->users_id),
        ];
        $update = [
            'selected' => $param['selectedAll'],
            'update_time' => getTime()
        ];
        $resultID = $this->shopCartDb->where($where)->update($update);
        if (!empty($resultID)) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    // 计算购物车选中数商品总价、选中商品数、是否全选
    private function getCartGoodsHandleResult($usersID = 0, $shopOpenSpec = 0, $usersDiscount = 1)
    {
        $where = [
            'a.abnormal' => 0,
            'a.users_id' => intval($usersID),
            'b.arcrank'  => array('egt', 0)
        ];
        $field = 'a.cart_id, a.product_id, a.product_num, a.spec_value_id, a.selected, b.users_price, c.spec_price';
        $shopCart = Db::name('shop_cart')->alias('a')
            ->where($where)
            ->field($field)
            ->join('__ARCHIVES__ b', 'a.product_id = b.aid', 'LEFT')
            ->join('__PRODUCT_SPEC_VALUE__ c', 'a.spec_value_id = c.spec_value_id and a.product_id = c.aid', 'LEFT')
            ->select();
        // 选中数商品总价、选中商品数、是否全选
        $cartTotalPrice = $selectedNumber = 0;
        foreach ($shopCart as $key => $value) {
            // 商品价格
            $goodsPrice = !empty($value['users_price']) ? floatval($value['users_price']) : 0;
            // 存在规格则使用规格价格
            if (!empty($value['spec_price']) && !empty($value['spec_value_id'])) $goodsPrice = floatval($value['spec_price']);
            // 会员有折扣则计算折扣后的价格
            if (!empty($usersDiscount)) $goodsPrice = sprintf("%.2f", $goodsPrice * $usersDiscount);
            if (1 === intval($value['selected'])) {
                // 选中数
                $selectedNumber++;
                // 选中的商品总价
                $cartTotalPrice += floatval($goodsPrice) * floatval($value['product_num']);
            }
        }
        // 是否全选
        $selectedAll = intval(count($shopCart)) === intval($selectedNumber) ? 1 : 0;

        // 结果返回
        return [
            'selectedAll' => $selectedAll,
            'selectedNumber' => $selectedNumber,
            'cartTotalPrice' => unifyPriceHandle($cartTotalPrice),
        ];
    }
}